package com.example.fruitshop;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MarketActivity extends AppCompatActivity {
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_market);

        this.listView = findViewById(R.id.list_product);
        this.listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        Button button = findViewById(R.id.btn_buy);

        this.listView.setOnItemClickListener(((adapterView, view, position, id) -> {
            CheckedTextView v = (CheckedTextView) view;
            boolean currentCheck = v.isChecked();
            Product product = (Product) listView.getItemAtPosition(position);
            product.setActive(!currentCheck);
        }));

        button.setOnClickListener(view -> submitSelectedProducts());
        this.initProductsData();
    }

    private void initProductsData() {
        String material = "apple,banana,cherry,grape,watermelon";
        List<String> fruitsList = new ArrayList<>(Arrays.asList(material.split(",")));
        List<Product> products = new ArrayList<>();
        for (String productName : fruitsList) {
            Product p = new Product(productName);
            products.add(p);
        }
        ArrayAdapter<Product> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_multiple_choice, products);
        this.listView.setAdapter(arrayAdapter);

        for (int i = 0; i < products.size(); i++) {
            this.listView.setItemChecked(i, products.get(i).isActive());
        }
    }

    private void submitSelectedProducts() {
        SparseBooleanArray sp = listView.getCheckedItemPositions();
        ArrayList<Product> selected = new ArrayList<>();
        for (int i = 0; i < sp.size(); i++) {
            if (sp.valueAt(i)) {
                selected.add((Product) listView.getItemAtPosition(i));
            }
        }
        Intent result = new Intent(MarketActivity.this, OrderActivity.class);
        result.putExtra("selectedProducts", selected);
        setResult(Activity.RESULT_OK, result);
        finish();
    }
}